﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;

namespace aerowan.server.Database
{
    public class AccountsDAO
    {
        /// <summary>
        /// Account insertion method has a mutex to prevent concurrent ID generation
        /// </summary>
        static object mtx_insert = new object();

        public static int Insert(string firstName, string lastName, string passwordHash)
        {
            MySqlConnection con = null;
            int result = -1;
            try
            {
                con = DAOManager.GetConnection();
                MySqlCommand cmd = new MySqlCommand("INSERT INTO accounts(first_name,last_name,password_hash) VALUES(@f, @l, @p)", con);
                cmd.Parameters.Add("@f", MySqlDbType.VarChar).Value = firstName;
                cmd.Parameters.Add("@l", MySqlDbType.VarChar).Value = lastName;
                cmd.Parameters.Add("@p", MySqlDbType.VarChar).Value = passwordHash;
                lock (mtx_insert)
                {
                    con.Open();
                    cmd.ExecuteNonQuery();
                    result = (int)cmd.LastInsertedId;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("AccountsDAO::Insert Exception: " + e.ToString());
                result = -1;
            }
            finally
            {
                DAOManager.CloseConnection(con);
            }
            return result;
        }

        public static bool Authenticate(int accountId, string password)
        {
            MySqlConnection con = null;
            bool result = false;
            try
            {
                con = DAOManager.GetConnection();
                MySqlCommand cmd = new MySqlCommand("SELECT COUNT(acct_id) FROM accounts WHERE acct_id = @id AND password_hash = @pass", con);
                cmd.Parameters.Add("@id", MySqlDbType.Int64).Value = accountId;
                cmd.Parameters.Add("@pass", MySqlDbType.VarChar).Value = password;
                con.Open();
                object res = cmd.ExecuteScalar();
                if (res != null) result = int.Parse(res.ToString()) == 1;
            }
            catch (Exception e)
            {
                Console.WriteLine("AccountsDAO::Authenticate Exception: " + e.ToString());
                result = false;
            }
            finally
            {
                DAOManager.CloseConnection(con);
            }
            return result;
        }
    }
}
